package org.ciallo.simplemusicplayer.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.PlayQueueAdapter;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.service.MediaPlayerService;
import org.ciallo.simplemusicplayer.util.Constants;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author Jukomu
 * @Description: 显示当前播放队列的底部弹出对话框Fragment。
 * 允许用户查看队列、切换歌曲、移除歌曲以及清空队列。
 * @Package: org.ciallo.simplemusicplayer.dialog
 * @Project: SimpleMusicPlayer
 * @name: PlayQueueDialogFragment
 * @Date: 2025/5/29-00:25
 * @Filename: PlayQueueDialogFragment
 */
public class PlayQueueDialogFragment extends BottomSheetDialogFragment {
    public static final String TAG = "PlayQueueDialog";

    private RecyclerView recyclerViewQueue;
    private PlayQueueAdapter adapter;
    private TextView tvPlayModeInfo;
    private ImageButton btnClearQueue;
    private TextView tvCloseDialog;
    private SharedViewModel sharedViewModel;
    private View dialogViewRoot;

    /**
     * 创建 PlayQueueDialogFragment 的新实例。
     *
     * @return PlayQueueDialogFragment 的一个新实例。
     */
    public static PlayQueueDialogFragment newInstance() {
        return new PlayQueueDialogFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.Theme_SimpleMusicPlayer_BottomSheetDialog);
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        Timber.d("PlayQueueDialog_Lifecycle: onCreate - SharedViewModel initialized: %b", (sharedViewModel != null));
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Timber.d("PlayQueueDialog_Lifecycle: onCreateDialog - Entry");
        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        // 移除了在这里 inflate 和 setContentView

        // BottomSheetBehavior 配置可以在 dialog.setOnShowListener 中进行
        dialog.setOnShowListener(dialogInterface -> {
            BottomSheetDialog d = (BottomSheetDialog) dialogInterface;
            // com.google.android.material.R.id.design_bottom_sheet 是 BottomSheetDialog 内部 FrameLayout 的 ID
            View bottomSheetInternal = d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
            if (bottomSheetInternal != null && dialogViewRoot != null) { // dialogViewRoot 是我们自己inflate的布局
                BottomSheetBehavior<?> behavior = BottomSheetBehavior.from(bottomSheetInternal);
                behavior.setSkipCollapsed(true);
                // 确保在视图测量后设置高度，以获得实际高度
                dialogViewRoot.post(() -> { // 使用 dialogViewRoot (我们自己的布局)
                    int measuredHeight = dialogViewRoot.getHeight();
                    int maxHeight = (int) (getResources().getDisplayMetrics().heightPixels * 0.75);
                    int peekHeight = (int) (getResources().getDisplayMetrics().heightPixels * 0.6);

                    ViewGroup.LayoutParams params = bottomSheetInternal.getLayoutParams();
                    if (params != null) {
                        if (measuredHeight > maxHeight) {
                            params.height = maxHeight;
                        } else {
                            params.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 或者 measuredHeight
                        }
                        bottomSheetInternal.setLayoutParams(params);
                    }
                    behavior.setPeekHeight(Math.min(peekHeight, measuredHeight > 0 ? measuredHeight : peekHeight));
                    behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                    Timber.d("PlayQueueDialog_Lifecycle: BottomSheet behavior configured. MeasuredHeight: %d, MaxHeight: %d, PeekHeightSet: %d", measuredHeight, maxHeight, behavior.getPeekHeight());
                });
            } else {
                Timber.w("PlayQueueDialog_Lifecycle: Could not configure BottomSheetBehavior - bottomSheetInternal or dialogViewRoot is null.");
            }
        });
        Timber.d("PlayQueueDialog_Lifecycle: onCreateDialog - Finished.");
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Timber.d("PlayQueueDialog_Lifecycle: onCreateView - Called.");
        // 在这里 inflate 布局并保存引用，然后返回它
        dialogViewRoot = inflater.inflate(R.layout.dialog_play_queue, container, false);
        return dialogViewRoot;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        // 这里的 'view' 参数现在是 onCreateView 返回的那个 view (dialogViewRoot)
        super.onViewCreated(view, savedInstanceState); // 确保调用父类
        Timber.d("PlayQueueDialog_Lifecycle: onViewCreated - Entry. View is from onCreateView: %b", view == dialogViewRoot);

        // 初始化视图控件
        recyclerViewQueue = view.findViewById(R.id.recyclerView_dialog_play_queue_list);
        tvPlayModeInfo = view.findViewById(R.id.textView_dialog_queue_play_mode_info);
        btnClearQueue = view.findViewById(R.id.button_dialog_queue_clear);
        tvCloseDialog = view.findViewById(R.id.textView_dialog_queue_close);

        Timber.d("PlayQueueDialog_Lifecycle: Views initialized. RecyclerView is null: %b", recyclerViewQueue == null);

        if (recyclerViewQueue != null) {
            setupRecyclerView();
        } else {
            Timber.e("PlayQueueDialog_Lifecycle: recyclerViewQueue is NULL after findViewById in onViewCreated!");
        }
        observePlaybackInfo();

        if (btnClearQueue != null) {
            btnClearQueue.setOnClickListener(v -> showClearQueueConfirmationDialog());
        }
        if (tvCloseDialog != null) {
            tvCloseDialog.setOnClickListener(v -> dismiss());
        }
        Timber.d("PlayQueueDialog_Lifecycle: onViewCreated - Listeners and observer setup complete.");
    }

    private void setupRecyclerView() {
        // ... (setupRecyclerView 内容不变，但确保里面的 Timber 日志存在) ...
        if (recyclerViewQueue == null || getContext() == null) {
            Timber.e("PlayQueueDialog_SetupRV: RecyclerView or Context is NULL before setting adapter!");
            return;
        }
        adapter = new PlayQueueAdapter(
                (clickedSong, positionInDisplayedList) -> {
                    if (sharedViewModel != null && clickedSong != null) {
                        Timber.d("PlayQueueDialog_ItemClick: Playing song: %s (ID: %d)", clickedSong.getTitle(), clickedSong.getId());
                        sharedViewModel.playSongByIdInCurrentQueue(clickedSong.getId());
                        dismiss();
                    } else {
                        Timber.e("PlayQueueDialog_ItemClick: SharedViewModel or clickedSong is null.");
                        if (getContext() != null) Toast.makeText(getContext(), "无法播放所选歌曲", Toast.LENGTH_SHORT).show();
                    }
                },
                (song, position) -> {
                    if (sharedViewModel != null && song != null) {
                        Timber.d("PlayQueueDialog_RemoveClick: Removing song: %s (ID: %d)", song.getTitle(), song.getId());
                        sharedViewModel.removeSongFromQueue(song.getId());
                        if (getContext() != null) Toast.makeText(getContext(), "\"" + song.getTitle() + "\" 已从队列移除", Toast.LENGTH_SHORT).show();
                    }
                }
        );
        recyclerViewQueue.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewQueue.setAdapter(adapter);
        Timber.d("PlayQueueDialog_SetupRV: Adapter set to RecyclerView. Adapter is null: %b", adapter == null);

    }

    /**
     * 观察 MediaPlayerService 的播放信息 LiveData 以更新UI。
     */
    private void observePlaybackInfo() {
        if (sharedViewModel == null) {
            Timber.e("PlayQueueDialog_Observe: SharedViewModel is null in observePlaybackInfo. Cannot observe playback state.");
            return;
        }
        Timber.d("PlayQueueDialog_Observe: Setting up LiveData observer.");

        MediaPlayerService.PlaybackInfo currentValue = sharedViewModel.playbackInfo.getValue();
        if (currentValue == null) {
            Timber.d("PlayQueueDialog_Observe: playbackInfo.getValue() is NULL before observing.");
        } else {
            Timber.d("PlayQueueDialog_Observe: Value BEFORE observe - Song: %s, ActiveQueue size: %d",
                    (currentValue.song != null ? currentValue.song.getTitle() : "null"),
                    (currentValue.activeQueue != null ? currentValue.activeQueue.size() : 0));
            if (currentValue.activeQueue != null && !currentValue.activeQueue.isEmpty()) {
                Timber.d("PlayQueueDialog_Observe: Value BEFORE observe - First song in activeQueue: %s", currentValue.activeQueue.get(0).getTitle());
            }
        }

        sharedViewModel.playbackInfo.observe(getViewLifecycleOwner(), playbackInfo -> {
            Timber.d("PlayQueueDialog_Observe_Entry: Observer callback triggered. PlaybackInfo is null: %b", playbackInfo == null);

            if (!isAdded() || getContext() == null) {
                Timber.w("PlayQueueDialog_Observe: Fragment not added or context is null, exiting observer.");
                return;
            }

            if (playbackInfo == null) {
                Timber.i("PlayQueueDialog_Observe: PlaybackInfo is null in callback. Displaying 'queue unavailable'.");
                if (tvPlayModeInfo != null) tvPlayModeInfo.setText("播放队列不可用");
                if (adapter != null) adapter.updateQueueAndCurrentSong(new ArrayList<>(), Constants.INVALID_INDEX);
                if (btnClearQueue != null) btnClearQueue.setEnabled(false);
                return;
            }

            Timber.d("PlayQueueDialog_Observe_Callback: PlaybackInfo.song: %s", (playbackInfo.song != null ? playbackInfo.song.getTitle() : "null"));
            Timber.d("PlayQueueDialog_Observe_Callback: PlaybackInfo.activeQueue size: %d", (playbackInfo.activeQueue != null ? playbackInfo.activeQueue.size() : 0));
            if (playbackInfo.activeQueue != null && !playbackInfo.activeQueue.isEmpty()) {
                Timber.d("PlayQueueDialog_Observe_Callback: First song in activeQueue: %s", playbackInfo.activeQueue.get(0).getTitle());
            }

            List<Song> displayQueue = playbackInfo.activeQueue;
            if (displayQueue == null) {
                displayQueue = new ArrayList<>();
                Timber.w("PlayQueueDialog_Observe_Callback: playbackInfo.activeQueue was null, defaulting to empty list.");
            }
            Timber.d("PlayQueueDialog_Observe_Callback: displayQueue size before submitList: %d", displayQueue.size());


            if (tvPlayModeInfo != null) {
                String modeText;
                switch (playbackInfo.playMode) {
                    case Constants.PLAY_MODE_SHUFFLE: modeText = getString(R.string.play_mode_shuffle_text); break;
                    case Constants.PLAY_MODE_SINGLE_LOOP: modeText = getString(R.string.play_mode_single_loop_text); break;
                    case Constants.PLAY_MODE_LIST_LOOP: modeText = getString(R.string.play_mode_list_loop_text); break;
                    case Constants.PLAY_MODE_ORDER: default: modeText = getString(R.string.play_mode_order_text); break;
                }
                tvPlayModeInfo.setText(String.format(Locale.getDefault(), "%s (%d首)", modeText, displayQueue.size()));
            }
            if (btnClearQueue != null) btnClearQueue.setEnabled(!displayQueue.isEmpty());

            long currentSongId = (playbackInfo.song != null) ? playbackInfo.song.getId() : Constants.INVALID_INDEX;
            if (adapter != null) {
                adapter.updateQueueAndCurrentSong(new ArrayList<>(displayQueue), currentSongId);
            } else {
                Timber.e("PlayQueueDialog_Observe_Callback: Adapter is null when trying to update queue!");
            }

            if (!displayQueue.isEmpty() && playbackInfo.song != null) {
                int currentDisplayIndex = -1;
                for (int i = 0; i < displayQueue.size(); i++) {
                    if (displayQueue.get(i).getId() == playbackInfo.song.getId()) {
                        currentDisplayIndex = i;
                        break;
                    }
                }
                if (currentDisplayIndex != -1 && recyclerViewQueue != null && recyclerViewQueue.getLayoutManager() != null) {
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerViewQueue.getLayoutManager();
                    int firstVisible = layoutManager.findFirstCompletelyVisibleItemPosition();
                    int lastVisible = layoutManager.findLastCompletelyVisibleItemPosition();
                    if (currentDisplayIndex < firstVisible || currentDisplayIndex > lastVisible) {
                        // 平滑滚动可能在 DialogFragment 的快速显示/隐藏中有问题，简单滚动
                        layoutManager.scrollToPositionWithOffset(currentDisplayIndex, (recyclerViewQueue.getHeight() / 2) - (recyclerViewQueue.getChildAt(0)!=null ? recyclerViewQueue.getChildAt(0).getHeight()/2 : 0) );
                    }
                }
            }
        });
        Timber.d("PlayQueueDialog_Observe: LiveData observer set up.");
    }

    /**
     * 显示清空播放队列的确认对话框。
     */
    private void showClearQueueConfirmationDialog() {
        if (getContext() == null) return;
        new AlertDialog.Builder(requireContext())
                .setTitle("清空播放队列")
                .setMessage("确定要清空当前播放队列中的所有歌曲吗？此操作会停止当前播放。")
                .setPositiveButton(R.string.ok, (dialog, which) -> {
                    if (sharedViewModel != null) {
                        sharedViewModel.clearQueue(); // 通过 SharedViewModel
                    }
                    dismiss();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    @Override
    public void onDestroyView() {
        Timber.d("PlayQueueDialog_Lifecycle: onDestroyView called.");
        if (recyclerViewQueue != null) {
            recyclerViewQueue.setAdapter(null);
        }
        dialogViewRoot = null; // 清除视图引用
        super.onDestroyView();
    }
}

